var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

const userMap = {
  'liyu': '123456'
}

router.post('/api/login', async (req, res, next) => {
  const { account, password } = req.body
  console.log('body: ', req.body)
  console.log('cookies: ', req.cookies)
  if (account) {
    if (userMap[account] === password) {
      res.cookie('authCode', account + '_' + password, { maxAge: 1000000 * 60 * 60, httpOnly: true, sameSite: 'none', secure: true })
      // res.header('set-cookie', `authCode=${account + '_' + password};`)
      res.send({
        code: 0,
        message: '登录成功'
      })
      return
    }
  }
  res.send({
    code: 1,
    message: '登录失败'
  })
})

router.post('/api/checkLogin', async (req, res, next) => {
  const { authCode } = req.cookies
  if (authCode) {
    const [account, password] = authCode.split('_')
    if (userMap[account] === password) {
      res.send({
        code: 0,
        message: 'ok',
        data: authCode
      })
      return
    }
  }
  res.send({
    code: 1,
    message: 'no',
  })
})

router.post('/api/getCookies', async(req, res, next) => {
  console.log(req.cookies)
  res.send({
    code: 0,
    message: 'ok',
    data: req.cookies
  })
})

module.exports = router;
